//+------------------------------------------------------------------+
//|                                                          222.mq5 |
//|                                  Copyright 2025, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2025, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"

// 移除重复的定义，依赖主代码传递的 SYMBOL_TO_CHECK
// #define SYMBOL_TO_CHECK "GOLD"

// 定义一个足够大的常量来表示数组最大长度
#define MAX_HISTORY 1000
// 定义 g_Loss 的最小值宏
//#define MIN_G_LOSS 0.01

// 定义数组用于存储盈亏情况、欧美开仓时间和中国开仓时间
int profitLossArray[MAX_HISTORY];
datetime openTimeEU[MAX_HISTORY];
datetime openTimeChina[MAX_HISTORY];
// 数组当前索引
int arrayIndex = 0;
// 全局变量，根据连续亏损次数更新，改为 double 类型
double g_Loss = MIN_G_LOSS;

// 新增标志位
int lastClosedOrderIsBuy = -1;      //多1，空0
int lastClosedOrderIsProfit = -1;   //盈利1，亏损0

// 清空数组和重置 arrayIndex
void ClearArrays()
{
    ArrayInitialize(profitLossArray, 0);
    ArrayInitialize(openTimeEU, 0);
    ArrayInitialize(openTimeChina, 0);
    arrayIndex = 0;
    lastClosedOrderIsBuy = -1;
    lastClosedOrderIsProfit = -1;
}

//+------------------------------------------------------------------+
//| 打印已关闭的指定品种订单信息                                         |
//+------------------------------------------------------------------+
void PrintClosedOrders()
{
    HistorySelect(0, TimeCurrent());
    int dealsTotal = HistoryDealsTotal();
    double totalProfit = 0;
    double totalLoss = 0;
    const int CHINA_TIME_OFFSET = 8 * 60 * 60; // 中国时区（UTC+8）的偏移量，单位为秒
    int lastClosedDealIndex = -1;

    // 先找到最后一个平仓的指定品种的交易索引
    for (int i = dealsTotal - 1; i >= 0; i--)
    {
        int deal_ticket = HistoryDealGetTicket(i);
        if (deal_ticket > 0)
        {
            string symbol = HistoryDealGetString(deal_ticket, DEAL_SYMBOL);
            int direction = HistoryDealGetInteger(deal_ticket, DEAL_ENTRY);
            if (symbol == SYMBOL_TO_CHECK && direction == DEAL_ENTRY_OUT)
            {
                lastClosedDealIndex = i;
                break;
            }
        }
    }

    for (int i = 0; i < dealsTotal; i++)
    {
        int deal_ticket = HistoryDealGetTicket(i);
        if (deal_ticket > 0)
        {
            datetime close_time = HistoryDealGetInteger(deal_ticket, DEAL_TIME);
            int order_ticket = HistoryDealGetInteger(deal_ticket, DEAL_ORDER);
            string symbol = HistoryDealGetString(deal_ticket, DEAL_SYMBOL);
            int deal_type = HistoryDealGetInteger(deal_ticket, DEAL_TYPE);
            int direction = HistoryDealGetInteger(deal_ticket, DEAL_ENTRY);
            double volume = HistoryDealGetDouble(deal_ticket, DEAL_VOLUME);
            double price = HistoryDealGetDouble(deal_ticket, DEAL_PRICE);
            double profit = HistoryDealGetDouble(deal_ticket, DEAL_PROFIT);

            if (symbol == SYMBOL_TO_CHECK && direction == DEAL_ENTRY_OUT)
            {
                datetime open_time = 0;
                if (HistoryOrderSelect(order_ticket))
                {
                    open_time = HistoryOrderGetInteger(order_ticket, ORDER_TIME_SETUP);
                    if (open_time == 0)
                    {
                        Print("获取开仓时间失败，订单号: ", order_ticket);
                    }
                }
                else
                {
                    Print("HistoryOrderSelect 调用失败，订单号: ", order_ticket);
                }

                // 计算中国时间
                datetime open_time_china = open_time + CHINA_TIME_OFFSET;
                datetime close_time_china = close_time + CHINA_TIME_OFFSET;

                if (profit > 0)
                {
                    totalProfit += profit;
                    profitLossArray[arrayIndex] = 1; // 盈利赋值为1
                }
                else if (profit < 0)
                {
                    totalLoss += profit;
                    profitLossArray[arrayIndex] = 2; // 亏损赋值为2
                }

                // 存储开仓时间
                openTimeEU[arrayIndex] = open_time;
                openTimeChina[arrayIndex] = open_time_china;
                arrayIndex++;

                // 第一行打印时间信息
                /*Print("开仓(欧美): ", TimeToString(open_time, TIME_DATE | TIME_SECONDS), 
                      ", 开仓(中国): ", TimeToString(open_time_china, TIME_DATE | TIME_SECONDS), 
                      ", 平仓(欧美): ", TimeToString(close_time, TIME_DATE | TIME_SECONDS), 
                      ", 平仓(中国): ", TimeToString(close_time_china, TIME_DATE | TIME_SECONDS));*/

                // 第二行打印其他订单信息
                //Print("单号: ", deal_ticket, ", 类型: ", deal_type == DEAL_TYPE_BUY? "卖" : "买", ", 手数: ", volume, ", 盈利: ", profit);

                // 更新最后一单的标志位
                if (i == lastClosedDealIndex)
                {
                    lastClosedOrderIsBuy = (deal_type == DEAL_TYPE_BUY)? 0 : 1;
                    lastClosedOrderIsProfit = (profit > 0)? 1 : 0;
                }
            }
        }
    }

    // 打印最后一单的信息
    if (lastClosedDealIndex != -1)
    {
        int lastClosedDealTicket = HistoryDealGetTicket(lastClosedDealIndex);
        double lastVolume = HistoryDealGetDouble(lastClosedDealTicket, DEAL_VOLUME);
        double lastProfit = HistoryDealGetDouble(lastClosedDealTicket, DEAL_PROFIT);
        Print("最后一单单号: ", lastClosedDealTicket, ", 手数: ", lastVolume, ", 盈利: ", lastProfit);
        Print("最后一单是否为多单标志位: ", lastClosedOrderIsBuy);
        Print("最后一单是否盈利标志位: ", lastClosedOrderIsProfit);
    }

    //Print(SYMBOL_TO_CHECK "总盈利: ", totalProfit, ", 总亏损: ", totalLoss);
}

//+------------------------------------------------------------------+
//| 打印盈亏数组的值及开仓时间和 g_Loss 值，同时判断连续亏损次数     |
//+------------------------------------------------------------------+
void PrintProfitLossArray()
{
   // Print("盈亏数组的值及开仓时间:");
    for (int i = 0; i < arrayIndex; i++)
    {
        //Print("数组[", i, "] = ", profitLossArray[i]);
        //Print("欧美开仓时间: ", TimeToString(openTimeEU[i], TIME_DATE | TIME_SECONDS));
        //Print("中国开仓时间: ", TimeToString(openTimeChina[i], TIME_DATE | TIME_SECONDS));
    }

    // 从最后一单开始判断连续亏损次数
    int consecutiveLosses = 0;
    for (int i = arrayIndex - 1; i >= 0; i--)
    {
        if (profitLossArray[i] == 2)
        {
            consecutiveLosses++;
        }
        else
        {
            break;
        }
    }

    Print("连续亏损次数: ", consecutiveLosses);
/*
    // 根据连续亏损次数更新 g_Loss
    if (consecutiveLosses >= 0 && consecutiveLosses <= 1) 
    {
        g_Loss = MIN_G_LOSS;
    } 
    else if (consecutiveLosses ==2)
    {
        g_Loss = MIN_G_LOSS * 2.0; // 这里明确用 double 类型的 2.0
    } 
    else if (consecutiveLosses == 3)
    {
        g_Loss = MIN_G_LOSS * 3.0; // 这里明确用 double 类型的 4.0
    } 
    else if (consecutiveLosses == 4)
    {
        g_Loss = MIN_G_LOSS * 4.0; // 这里明确用 double 类型的 4.0
    } 
    else if (consecutiveLosses == 5) 
    {
        g_Loss = MIN_G_LOSS * 6.0; // 这里明确用 double 类型的 8.0
    } 
    else if (consecutiveLosses == 6) 
    {
        g_Loss = MIN_G_LOSS * 9.0; // 这里明确用 double 类型的 8.0
    } 
    else if (consecutiveLosses == 7) 
    {
        g_Loss = MIN_G_LOSS * 14.0; // 这里明确用 double 类型的 8.0
    } 
     else if (consecutiveLosses == 8) 
    {
        g_Loss = MIN_G_LOSS * 21.0; // 这里明确用 double 类型的 8.0
    } 
     else if (consecutiveLosses == 9) 
    {
        g_Loss = MIN_G_LOSS * 31.0; // 这里明确用 double 类型的 8.0
    } 
     else if (consecutiveLosses == 10) 
    {
        g_Loss = MIN_G_LOSS * 47.0; // 这里明确用 double 类型的 8.0
    } 
     else if (consecutiveLosses == 11) 
    {
        g_Loss = MIN_G_LOSS * 70.0; // 这里明确用 double 类型的 8.0
    } 
    else if (consecutiveLosses == 12) 
    {
        g_Loss = MIN_G_LOSS * 105.0; // 这里明确用 double 类型的 8.0
    } 
    else if (consecutiveLosses == 13) 
    {
        g_Loss = MIN_G_LOSS * 157.0; // 这里明确用 double 类型的 8.0
    } 
    else 
    {
       g_Loss=0;
    }
*/
   // 根据连续亏损次数更新 g_Loss
   if (consecutiveLosses >= 0 && consecutiveLosses <= 1) 
   {
       g_Loss = MIN_G_LOSS;
   } 
   else if (consecutiveLosses ==2)
   {
       g_Loss = MIN_G_LOSS * 1.0; // 这里明确用 double 类型的 2.0
   } 
   else if (consecutiveLosses == 3)
   {
       g_Loss = MIN_G_LOSS * 2.0; // 这里明确用 double 类型的 4.0
   } 
   else if (consecutiveLosses == 4)
   {
       g_Loss = MIN_G_LOSS * 2.0; // 这里明确用 double 类型的 4.0
   } 
   else if (consecutiveLosses == 5) 
   {
       g_Loss = MIN_G_LOSS * 3.0; // 这里明确用 double 类型的 8.0
   } 
   else if (consecutiveLosses == 6) 
   {
       g_Loss = MIN_G_LOSS * 4.0; // 这里明确用 double 类型的 8.0
   } 
   else if (consecutiveLosses == 7) 
   {
       g_Loss = MIN_G_LOSS * 5.0; // 这里明确用 double 类型的 8.0
   } 
    else if (consecutiveLosses == 8) 
   {
       g_Loss = MIN_G_LOSS * 7.0; // 这里明确用 double 类型的 8.0
   } 
    else if (consecutiveLosses == 9) 
   {
       g_Loss = MIN_G_LOSS * 9.0; // 这里明确用 double 类型的 8.0
   } 
    else if (consecutiveLosses == 10) 
   {
       g_Loss = MIN_G_LOSS * 12.0; // 这里明确用 double 类型的 8.0
   } 
    else if (consecutiveLosses == 11) 
   {
       g_Loss = MIN_G_LOSS * 16.0; // 这里明确用 double 类型的 8.0
   } 
   else if (consecutiveLosses == 12) 
   {
       g_Loss = MIN_G_LOSS * 22.0; // 这里明确用 double 类型的 8.0
   } 
   else if (consecutiveLosses == 13) 
   {
       g_Loss = MIN_G_LOSS * 29.0; // 这里明确用 double 类型的 8.0
   } 
   else if (consecutiveLosses == 14) 
   {
       g_Loss = MIN_G_LOSS * 39.0; // 这里明确用 double 类型的 8.0
   } 
   else if (consecutiveLosses == 15) 
   {
       g_Loss = MIN_G_LOSS * 51.0; // 这里明确用 double 类型的 8.0
   } 
   else if (consecutiveLosses == 16) 
   {
       g_Loss = MIN_G_LOSS * 68.0; // 这里明确用 double 类型的 8.0
   } 
   else if (consecutiveLosses == 17) 
   {
       g_Loss = MIN_G_LOSS * 91.0; // 这里明确用 double 类型的 8.0
   } 
   else if (consecutiveLosses == 18) 
   {
       g_Loss = MIN_G_LOSS * 121.0; // 这里明确用 double 类型的 8.0
   } 
   else if (consecutiveLosses == 19) 
   {
       g_Loss = MIN_G_LOSS * 161.0; // 这里明确用 double 类型的 8.0
   } 
   else 
   {
      g_Loss=0;
   }
    //Print("更新后的 g_Loss 值: ", g_Loss);
}

// 判断当前有没有单的函数
int IsAnyOrderOpen(void)
{
    int positionCount = PositionsTotal();
    
    if(positionCount>0)
    {
        //Print("有单");
        return 1;
    }
    else
    {
        //Print("无单");
        return 0;
    }
}

// 新增 TimeTransformat 函数
void TimeTransformat()
{
    const int CHINA_TIME_OFFSET = 8 * 60 * 60; // 中国时区（UTC+8）的偏移量，单位为秒
    datetime currentTime = TimeCurrent();
    datetime chinaTime = currentTime + CHINA_TIME_OFFSET;
    MqlDateTime dt;
    TimeToStruct(chinaTime, dt);
    int hour = dt.hour;
    int a = 0;

    if (hour >= 14 && hour < 21)
    {
        a = 1;
    }

    Print("当前北京时间: ", TimeToString(chinaTime, TIME_DATE | TIME_SECONDS));
    Print("当前欧美时间: ", TimeToString(currentTime, TIME_DATE | TIME_SECONDS));
    Print("a 的值: ", a);
}

// 封装的处理函数
bool ProcessOrders()
{
    ClearArrays(); // 清空数组和重置 arrayIndex
    PrintClosedOrders();
    PrintProfitLossArray();
    IsAnyOrderOpen();
    TimeTransformat(); // 调用 TimeTransformat 函数
    return true;
}